package repository

import (
	"fmt"
	"log"

	"github.com/hashicorp/consul/api"
	"github.com/jinzhu/gorm"
)

type ConsulServiceData struct {
	gorm.Model
	ServiceType      string `json:"service_type"`
	ShortName        string `json:"short_name"`
	Hostname         string `json:"hostname"`
	Address          string `json:"address"`
	Datacenter       string `json:"datacenter"`
	Node             string `json:"consul_node"`
	PrometheusServer string `json:"server"`
	AppTeam          string `json:"app_team"`
	ServiceName      string `json:"service_name"`
	SystemID         string `json:"system_id"`
	Port             int    `json:"port"`
	ServiceID        string `json:"service_id"`
}

type ConsulApi struct {
	client *api.Client
}

// 初始化函数
func (c *ConsulApi) Init(address string) *ConsulApi {
	// 创建 Consul 客户端
	config := api.DefaultConfig()
	// config.Address = "192.168.100.151:8085"
	config.Address = address
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	return &ConsulApi{
		client: client,
	}
}

// 服务注册
func (c *ConsulApi) RegisterService(service api.AgentServiceRegistration) bool {

	// 注册服务
	err := c.client.Agent().ServiceRegister(&service)
	if err != nil {
		log.Printf("%v register failed, error is: %v", service.ID, err)
		return false
	} else {
		return true
	}

}

// 注销服务
func (c *ConsulApi) DeregisterService(service_id string) bool {
	err := c.client.Agent().ServiceDeregister(service_id)
	if err != nil {
		log.Printf("%v deregister failed, error is: %v", service_id, err)
		return false
	} else {
		return true
	}
	// fmt.Println("Service deregistered")
}

// 检查服务是否存在
func (c *ConsulApi) CheckService(service_id string) bool {

	agent := c.client.Agent()
	service, _, err := agent.Service(service_id, nil)

	if err != nil {
		// log.Panicf("获取服务信息失败: %v", err)
		// fmt.Println("获取服务信息失败:", err)
		return false
	} else {
		fmt.Println("ID:", service.ID)
		return true
	}
}

// 检查服务健康状况
func (c *ConsulApi) CheckServiceStatus() {
	health := c.client.Health()
	checks, _, err := health.State(api.HealthPassing, nil)
	if err != nil {
		fmt.Println("获取服务健康状况失败:", err)
		return
	}

	// 遍历健康检查列表并打印结果
	for _, check := range checks {
		fmt.Printf("服务ID: %s, 健康状态: %s\n", check.ServiceID, check.Status)
	}
}

// 获取服务信息
func (c *ConsulApi) GatherService() []ConsulServiceData {
	// 调用 Catalog API 获取所有服务信息
	catalog := c.client.Catalog()
	// 服务类型
	services, _, err := catalog.Services(nil)

	if err != nil {
		panic(err)
	}
	var jsonData []ConsulServiceData

	// 打印服务名和对应的地址
	for name, _ := range services {
		fmt.Println("-------------------------", name)
		servicesData, _, _ := catalog.Service(name, "", nil)
		for _, service := range servicesData {
			var Server string
			lenTags := len(service.ServiceTags)
			if lenTags > 0 {
				Server = service.ServiceTags[0]
			} else {
				Server = "None"
			}

			data := ConsulServiceData{
				ServiceType:      service.ServiceName,
				ShortName:        service.ServiceMeta["short_name"],
				Hostname:         service.ServiceMeta["hostname"],
				Address:          service.ServiceAddress,
				Datacenter:       service.Datacenter,
				Node:             service.Node,
				PrometheusServer: Server,
				AppTeam:          service.ServiceMeta["app_team"],
				ServiceName:      service.ServiceMeta["service_name"],
				SystemID:         service.ServiceMeta["system_id"],
				Port:             service.ServicePort,
				ServiceID:        service.ServiceID,
			}
			jsonData = append(jsonData, data)

		}
	}
	return jsonData
}

// 写kv
func (c *ConsulApi) WriteKV() {
	// 调用 KV API 写入配置信息
	kv := c.client.KV()
	pair := &api.KVPair{Key: "fffff", Value: []byte("gggg")}
	_, err := kv.Put(pair, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println("-----------------------------------")
}

// 读kv
func (c *ConsulApi) ReadKV() {
	kv := c.client.KV()
	value, _, err := kv.Get("example", nil)
	if err != nil {
		panic(err)
	}
	fmt.Println("a", string(value.Value))
}

// 工厂函数，执行初始化
func CreateConsulClient(address string) *ConsulApi {
	consulApi := ConsulApi{}
	return consulApi.Init(address)
}
